//
//  LGPatientWeightChart.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/6.
//  体重统计图

#import "LGPatientWeightChart.h"

#import "LGScrollView.h"
#define topMargin    viewPix(60)

#define leftMargin   viewPix(35)+iPadMargin(10)

#define lineHeight   viewPix(35)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight  (lineHeight*6+viewPix(20))

@interface LGPatientWeightChart()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UILabel *titleLabel;

/**   */
@property (nonatomic , strong)UILabel *dayLabel;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)UILabel *waistlineUnit;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**  腰围 */
@property (nonatomic , strong)UIButton *waistlineButton;
/**  体重 */
@property (nonatomic , strong)UIButton *weightButton;
/**   */
@property (nonatomic , strong)UIView *obesityLine;
/**   */
@property (nonatomic , strong)UIView *overweightLine;
/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**  体重 */
@property (nonatomic , strong)NSArray *weightArray;
/**  腰围 */
@property (nonatomic , strong)NSArray *waistlineArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;

@end

@implementation LGPatientWeightChart

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0) {
        self.totalCount = [dataDic[@"xAxis"] count]>0?[dataDic[@"xAxis"] count]:1;
        NSInteger count = (self.totalCount>7)?7:self.totalCount;
        self.itemWidth = scrollWidth/count;
        self.scrollView.contentSize = CGSizeMake(viewPix(20)+self.itemWidth*self.totalCount, scrollHeight);
        [self.scrollView setContentOffset:CGPointMake(viewPix(20)+self.itemWidth*self.totalCount-scrollWidth-viewPix(10), 0)];
        self.dayArray = dataDic[@"xAxis"];
        self.weightArray = dataDic[@"seriesBmi"];
        self.waistlineArray = dataDic[@"seriesWaistline"];

        //体重上下限
        NSArray *weightab = dataDic[@"weightab"];
        self.overweightLine.hidden = weightab.count>1?NO:YES;
        if (weightab.count>1) {
            CGFloat weightTop = (200 - [dataDic[@"weightab"][1] integerValue])/40.0;
            CGFloat weightH = ([dataDic[@"weightab"][1] integerValue] - [dataDic[@"weightab"][0] integerValue])*(lineHeight/40.0);
            self.overweightLine.frame = CGRectMake(0, lineHeight*weightTop+lineHeight*0.5, self.itemWidth*30+viewPix(20), weightH);
        }
        
        //腰围上下限
        NSArray *waistline = dataDic[@"waistlineab"];
        self.obesityLine.hidden = waistline.count>1?NO:YES;
        if (waistline.count>1) {
            CGFloat obesity = (200 - [dataDic[@"waistlineab"][1] integerValue])/40.0;
            CGFloat obesityH = ([dataDic[@"waistlineab"][1] integerValue] - [dataDic[@"waistlineab"][0] integerValue])*(lineHeight/40.0);
            self.obesityLine.frame = CGRectMake(0, lineHeight*obesity+lineHeight*0.5, self.itemWidth*30+viewPix(20), obesityH);
        }
        
        //重合的label隐藏
//        CGRect obesityRect = CGRectMake(self.obesityLabel.frame.origin.x, self.obesityLabel.frame.origin.y+viewPix(5), self.obesityLabel.bounds.size.width, self.obesityLabel.bounds.size.height-viewPix(10));
//        CGRect overweightRect = CGRectMake(self.overweightLabel.frame.origin.x, self.overweightLabel.frame.origin.y+viewPix(5), self.overweightLabel.bounds.size.width, self.overweightLabel.bounds.size.height-viewPix(10));
//        for (NSInteger i=0; i<5; i++) {
//            UILabel *label = [self viewWithTag:500+i];
//            if(CGRectContainsPoint(obesityRect, label.center)||CGRectContainsPoint(overweightRect, label.center)){
//                label.hidden = YES;
//            }else{
//                label.hidden = NO;
//            }
//        }
    }
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSArray *tempArray = [LGNSString(dayArray[i]) componentsSeparatedByString:@"-"];
        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:dayString colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*5.5, self.itemWidth, lineHeight);
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
    }
}

-(void)setWeightArray:(NSArray *)weightArray{
    _weightArray = weightArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<weightArray.count; i++) {
        CGFloat pointY = scrollHeight-(([weightArray[i][@"value"] floatValue]-0)/40.0*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:@"体重-Normal" selectImage:@"体重-Select"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 2000+i;
        [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#429BFF"];
}

-(void)setWaistlineArray:(NSArray *)waistlineArray{
    _waistlineArray = waistlineArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<waistlineArray.count; i++) {
        NSString *value = LGNSString(waistlineArray[i][@"value"]);
        if(value.length>0){
            CGFloat pointY = scrollHeight-(([waistlineArray[i][@"value"] floatValue]-0)/40.0*lineHeight+viewPix(20)+lineHeight*0.5);
            UIButton *button = [UIButton buttonWithImage:@"腰围-Normal" selectImage:@"腰围-Select"];
            button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
            button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
            button.tag = 3000+i;
            [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
            [self.scrollView addSubview:button];
            NSValue *point = [NSValue valueWithCGPoint:button.center];
            [pointArray addObject:point];
        }
    }
    [self drawCurveLine:pointArray lineColor:@"#039D78"];
}


-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag%1000;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:2000+i];
        button.selected = (index == i)?YES:NO;
        
        UIButton *button2 = [self viewWithTag:3000+i];
        if(button2){
            button2.selected = (index == i)?YES:NO;
        }
    }
    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:waistline:date:point:)]){
        [self.delegate showAlertView:LGNSString(self.weightArray[index][@"value"]) waistline:LGNSString(self.waistlineArray[index][@"value"]) date:self.dayArray[index] point:point];
    }
    
    CGPoint point2 = [self.scrollView convertPoint:sender.center toView:self.superview.superview];
    if(self.delegate && [self.delegate respondsToSelector:@selector(showWeightAlertView:waistline:date:point:)]){
        [self.delegate showWeightAlertView:LGNSString(self.weightArray[index][@"value"]) waistline:LGNSString(self.waistlineArray[index][@"value"]) date:self.dayArray[index] point:point2];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:waistlineDic:date:point:)]) {
        [self.delegate showAlertView:self.weightArray[index] waistlineDic:self.waistlineArray[index] date:self.dayArray[index] point:point2];
    }
}


//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:2000+i];
        [self.scrollView bringSubviewToFront:button];
        
        UIButton *button2 = [self viewWithTag:3000+i];
        [self.scrollView bringSubviewToFront:button2];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)createSubView{
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.titleLabel];
    [self addSubview:self.baseView];
    [self addSubview:self.titleBtn];
    [self.baseView addSubview:self.dayLabel];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.waistlineUnit];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.waistlineButton];
    [self.baseView addSubview:self.weightButton];
    NSArray *titleArray = @[@"200",@"160",@"120",@"80",@"40",@"0"];
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        label.tag = 500+i;
        [self.baseView addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(20), lineHeight)];
        [self.scrollView addSubview:lineView];
    }

    [self.scrollView addSubview:self.overweightLine];
    [self.scrollView addSubview:self.obesityLine];
    [self.titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.baseView.mas_top).offset(12);
        make.left.right.equalTo(self.baseView);
        make.height.equalTo(@(viewPix(40)));
    }];
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"变化趋势" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(20), viewPix(16), viewPix(100), viewPix(23));
    }
    return _titleLabel;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35))];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 10;
    }
    return _baseView;
}

-(UIButton *)titleBtn{
    if(!_titleBtn){
        _titleBtn = [UIButton buttonWithTitle:@"体重" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#282828" frame:CGRectMake(0, kMinY(self.baseView.frame), Screen_W-viewPix(32), viewPix(40))];
        _titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, 0);
        _titleBtn.backgroundColor = [UIColor whiteColor];
        _titleBtn.cornerRidus = 10;
        _titleBtn.hidden = YES;
        UIImageView *tipView = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_W-viewPix(32)-viewPix(28), viewPix(12), viewPix(16), viewPix(16))];
        tipView.image = [UIImage imageNamed:@"grayTip16"];
        [_titleBtn addSubview:tipView];
    }
    return _titleBtn;
}

-(UILabel *)dayLabel{
    if(!_dayLabel){
        _dayLabel = [UILabel lableWithText:@"最近30天体重分布" colorString:@"#333333" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
        _dayLabel.frame = CGRectMake(viewPix(12), viewPix(10), viewPix(200), viewPix(23));
    }
    return _dayLabel;
}
-(UILabel *)waistlineUnit{
    if(!_waistlineUnit){
        _waistlineUnit = [UILabel lableWithText:@"腰围（cm）" colorString:@"#666666" textFont:LGFont(10) textAlignment:NSTextAlignmentLeft lines:1];
        _waistlineUnit.frame = CGRectMake(viewPix(12), topMargin-27, 80, viewPix(17));
    }
    return _waistlineUnit;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"体重（kg）" colorString:@"#666666" textFont:LGFont(10) textAlignment:NSTextAlignmentLeft lines:1];
        _unitLabel.frame = CGRectMake(viewPix(12), topMargin-10, 80, viewPix(17));
    }
    return _unitLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UIView *)overweightLine{
    if(!_overweightLine){
        _overweightLine = [[UIView alloc] init];
        _overweightLine.backgroundColor = [UIColor colorWithString:@"#429BFF" alpha:0.2];
    }
    return _overweightLine;
}


-(UIView *)obesityLine{
    if(!_obesityLine){
        _obesityLine = [[UIView alloc] init];
        _obesityLine.backgroundColor = [UIColor colorWithString:@"#81D899" alpha:0.2];
    }
    return _obesityLine;
}

-(UIButton *)waistlineButton{
    if(!_waistlineButton){
        _waistlineButton = [UIButton buttonWithTitle:@" 腰围" titleFont:LGFont(15) textColor:@"#333333" imageName:@"体重-腰围"];
        _waistlineButton.frame = CGRectMake((Screen_W-viewPix(32))/2.0-viewPix(100), kMaxY(self.scrollView.frame)-3, viewPix(100), viewPix(20));
        _waistlineButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _waistlineButton.userInteractionEnabled = NO;
    }
    return _waistlineButton;
}

-(UIButton *)weightButton{
    if(!_weightButton){
        _weightButton = [UIButton buttonWithTitle:@" 体重" titleFont:LGFont(15) textColor:@"#333333" imageName:@"体重-体重"];
        _weightButton.frame = CGRectMake(kMaxX(self.waistlineButton.frame), kMaxY(self.scrollView.frame)-3, viewPix(100), viewPix(20));
        _weightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _weightButton.userInteractionEnabled = NO;
    }
    return _weightButton;
}

@end
